package com.xxh.video.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxh.dataaccess.dao.CategoryDao;
import com.xxh.dataaccess.entity.Category;
import com.xxh.dataaccess.entity.Video;
import com.xxh.video.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service("CategoryService")
public class CateGoryServiceImpl extends ServiceImpl<CategoryDao, Category> implements CategoryService {


    @Override
    public List<Category> listWithTree() {
        List<Category> all = baseMapper.selectList(null);
        List<Category> categoryWithChildren = all.stream()
                //找出所有父节点
                .filter(category -> {
                    return category.getParentId() == 0;
                })
                //拿到父节点的子节点
                .map(father -> {
                    father.setChildren(getChildren(father, all));
                    return father;
                })
                //收集
                .collect(Collectors.toList());
        return categoryWithChildren;
    }

    @Override
    public List<Category> getSubMenus(String categoryName) {

        List<Category> all = baseMapper.selectList(null);
        QueryWrapper<Category> wrapper = new QueryWrapper<Category>().eq("name", categoryName);
        Category root =baseMapper.selectOne(wrapper);
        List<Category> list = all.stream().filter(item -> {
            return item.getParentId().equals(root.getCid());
        }).collect(Collectors.toList());
        return list;
    }

    @Override
    public List<Category> getSubMenus(Integer cid) {
        List<Category> all = baseMapper.selectList(null);
        Category root = baseMapper.selectById(cid);
        List<Category> list = all.stream().filter(item -> {
            return item.getParentId().equals(root.getCid());
        }).collect(Collectors.toList());
        return list;
    }


    /**
     * @param root 当前需要子求取节点的元素
     * @param all  所有的元素
     * @return 当前元素的所有子元素
     */
    private List<Category> getChildren(Category root, List<Category> all) {
        List<Category> list = all.stream().filter(item -> {
            return item.getParentId().equals(root.getCid());
        }).collect(Collectors.toList());
        return list;
    }
}
